package com.demo.context;

import com.alibaba.fastjson.JSON;
import com.demo.model.UserContext;
import com.demo.model.UserDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Base64;

@Slf4j
public class TransmitUserInfoFilter implements Filter {

    public TransmitUserInfoFilter() {}

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        this.initUserInfo((HttpServletRequest)request);
        chain.doFilter(request,response);
    }

    private void initUserInfo(HttpServletRequest request){
        String requestJson = request.getHeader(UserContext.KEY_USERINFO_IN_HTTP_HEADER);
        if (StringUtils.isNotBlank(requestJson)) {
            byte[] decodeByte = Base64.getDecoder().decode(requestJson);
            UserDto userInfo = JSON.parseObject(decodeByte, UserDto.class);
            UserContext.setUser(userInfo);
        }
    }

    @Override
    public void destroy() {}
}
